package com.example.controller;

import com.example.common.Result;
import com.example.common.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局错误控制器
 * 处理404等常见HTTP错误
 */
@RestController
public class GlobalExceptionController implements ErrorController {
    
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionController.class);
    
    /**
     * 处理所有错误
     */
    @RequestMapping("/error")
    public Result<String> handleError(HttpServletRequest request, HttpServletResponse response) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String requestURI = request.getRequestURI();
        String queryString = request.getQueryString();
        String method = request.getMethod();
        
        String fullPath = requestURI + (queryString != null ? "?" + queryString : "");
        
        logger.error("请求错误: {} {} {}, 状态码: {}", method, fullPath, requestURI, statusCode);
        
        if (statusCode == 404) {
            return Result.error(ResultCode.NOT_FOUND.getCode(), 
                    "请求的资源不存在: " + fullPath + " (方法: " + method + ")");
        } else if (statusCode == 403) {
            return Result.error(ResultCode.FORBIDDEN.getCode(), "没有权限访问该资源");
        } else if (statusCode == 405) {
            return Result.error(ResultCode.METHOD_NOT_ALLOWED.getCode(), "不支持的请求方法: " + method);
        } else if (statusCode == 400) {
            return Result.error(ResultCode.PARAM_ERROR.getCode(), "请求参数错误");
        } else if (statusCode == 415) {
            return Result.error(ResultCode.PARAM_ERROR.getCode(), "不支持的媒体类型");
        } else {
            return Result.error(ResultCode.ERROR.getCode(), "服务器内部错误 (" + statusCode + ")");
        }
    }
} 